import React, {useContext, useEffect, useState} from "react";
import {Icon, Input, ListItem, Text} from "react-native-elements";
import {
    ActivityIndicator,
    Alert,
    Button,
    Dimensions,
    ImageBackground,
    ScrollView,
    TouchableOpacity,
    View
} from "react-native";
import * as elements from "react-native-elements";
import LocaleContext from "../libs/locale";
import WalletContext, {checkPassword} from "../libs/wallet";
import {Image} from "react-native-elements/dist/image/Image";
import NFT_NULL from "../assets/Assets/NFT_NULL.png";
import {NFTView_TitleSize, sendNFT} from "../libs/NFTView";
import icon3 from "../assets/Assets/send.contracts.png";
import {checkAddress} from "../libs/keyPair";
import {constansts} from "../libs/constansts";
import {BottomSheet} from "react-native-elements/dist/bottomSheet/BottomSheet";
import {Overlay} from "react-native-elements/dist/overlay/Overlay";
import AsyncStorage from "@react-native-async-storage/async-storage";
import {Avatar} from "react-native-elements/dist/avatar/Avatar";
import logo from "../assets/logo.png";
import {timeFormat} from "../libs/helpers";
import WaitingModal from "../components/WaitingModal";
import icon1 from "../assets/Assets/send.receiver_address.png";

const {width,height,scale} = Dimensions.get("window");

const NFTSend = ({navigation,route}:any) => {
    const locale:any = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);
    const [NFT_ID, setNFT_ID] = useState(route?.params?.id);
    const [NFT_Item, setNFT_Item] = useState(route?.params?.item);
    const [NFT_Contract, setNFT_Contract] = useState(route?.params?.contract);

    //输入地址
    const [receiverError,setReceiverError] = useState("");
    const [receiver,setReceiver] = useState("")
    //最近交易地址及显示
    const [recentVisible, setRecentVisible] = useState(false);
    const [recentTxs, setRecentTxs]:any = useState([]);
    //密码错误
    const [pwdError, setPwdError] = useState('');
    //显示交易详情界面
    const [showDetailPage,setShowDetailPage]= useState(false);
    //显示输入密码界面
    const [showPwdPage,setShowPwdPage]= useState(false);
    const [pwdVisible, setPwdVisible] = useState(false);
    const [pwd, setPwd] = useState("");
    const [transfering, setTransfering] = useState(false);
    const [waiting, setWaiting] = useState(false);


    useEffect(()=>{
        navigation.setOptions({title: locale._("NFT_Transfer")})
    },[])

    const onSend = async () => {
        setPwdError("");

        let hasError = false;

        if (!receiver) {
            setReceiverError(`${locale._('enter')} ${locale._('Assets.send.receiver')}`);
            hasError = true;
        } else if (!checkAddress(receiver)) {
            setReceiverError(locale._('Assets.send.receiverInvalid'));
            hasError = true;
        } else if (receiver === wallet.address) {
            setReceiverError(locale._('Assets.send.cannotToSelf'));
            hasError = true;
        }

        if(parseFloat(constansts.SATcount) < 0.002)
        {
            Alert.alert("",locale._("serviceChargeError"))
            hasError = true;
        }

        if (hasError) {
            return;
        }
        setShowDetailPage(true);
    };

    const SendNFT = async () => {
        if(transfering)
        {
            console.log("转账中……");
            return;
        }
        setTransfering(true);
        if (!checkPassword(wallet, pwd)) {
            setPwdError(locale?._('Import.passwordError'));
            setTransfering(false);
            return;
        }
        setWaiting(true);
        try {
            let res = await sendNFT(wallet.seed, wallet.address, NFT_Contract, receiver, NFT_ID);
            if (res) {
                navigation.popToTop();
                navigation.push('Txs', {kind: 'Pending'})
                return;
            }
        }catch (e) {
            console.log(`SendNFTError-->`+e);
        }
        finally {
            setTransfering(false);
            setWaiting(false);
            setShowPwdPage(false);
        }

    }

    const onShowRecent = async () => {
        try {
            const NTA = await AsyncStorage.getItem("@nearTranAddress") || "[]";
            if (NTA && NTA !== "") {
                let recentTxsTemp;
                recentTxsTemp = JSON.parse(NTA);
                setRecentTxs(recentTxsTemp);
            }
            else
            {
                setRecentTxs([]);
            }
        } catch (e) {
            console.log('getTxs:', e);
        }finally {
            setRecentVisible(true);
        }


    };

    return (
        <View style={{flex:1,padding:15,paddingTop:10,backgroundColor:"rgb(246, 246, 246)"}}>
            <View style={{backgroundColor:"#fff",flexDirection:"column",padding:15,width:width-30,marginTop:10,marginBottom:10}}>
                <View style={{flexDirection:"row",alignItems:"center"}}>
                    <ImageBackground source={icon1} style={{width: NFTView_TitleSize*1.5, height: NFTView_TitleSize*1.5,marginRight:5}}/>
                    <Text style={{fontSize:NFTView_TitleSize,lineHeight:25}}>{locale._("NFT_Transfer_receiver")}</Text>
                </View>

                <Input
                    style={{fontSize: NFTView_TitleSize,padding:0,margin:0}}
                    // allowFontScaling={true}
                    underlineColorAndroid={'transparent'}
                    containerStyle={{padding:0,height:NFTView_TitleSize*2.5,width:"100%",marginLeft:-10,marginBottom:15}}
                    inputStyle={{padding:0,fontSize:NFTView_TitleSize,lineHeight:NFTView_TitleSize}}
                    inputContainerStyle={{padding:0,height:NFTView_TitleSize*2.5,margin:0}}
                    errorMessage={receiverError}
                    value={receiver}
                    onChangeText={(value) => {
                        setReceiverError('');
                        setReceiver(value.trim())
                    }}
                    onEndEditing={()=>{

                    }}
                    rightIcon={<Image
                        source={icon3}
                        style={{width: NFTView_TitleSize+5, height: NFTView_TitleSize+5}}
                        onPress={ async ()=>{
                            await onShowRecent()
                        }}
                    />}
                />
            </View>
            <View style={{backgroundColor:"#fff",flexDirection:"column",padding:15,width:width-30,marginTop:5,marginBottom:10}}>
                <Text style={{fontSize:NFTView_TitleSize,lineHeight:25}}>{locale._("NFT_Transfer_sendNFT")}</Text>
                <View style={{flexDirection:"row",alignItems:"center",marginTop:5}}>
                    <Image
                        source={NFT_Item.image!=undefined?{uri:NFT_Item.image}:NFT_NULL}
                        style={{ width: NFTView_TitleSize*4, height: NFTView_TitleSize*4 ,borderRadius:4}}
                        PlaceholderContent={<Image
                            style={{width:NFTView_TitleSize*4,height:NFTView_TitleSize*4, borderRadius:4}}
                            source={NFT_NULL}/>}
                    />
                    <Text style={{fontSize:NFTView_TitleSize,marginLeft:15}}>#{NFT_ID}</Text>
                </View>
            </View>
            <View style={{height:40,marginLeft:0,marginTop:7,marginBottom:13}}>
                <Text style={{color:"#734FDFFF",fontSize:15,marginLeft:5}}>{locale?._('Assets.send.Notice')} </Text>
            </View>
            <View style={{flex:1}}/>
            <View style={{padding:10,alignItems:"center",width:width}}>
                {/*<Button title={locale._("NFT_Transfer_send")} onPress={() => {*/}
                {/*    onSend()*/}
                {/*}}/>*/}
                {receiver ?
                    <elements.Button
                        type='outline'
                        title={locale?._('next')}
                        onPress={onSend}
                        // loading={sending}
                        // disabled={sending}
                        loadingProps={{color: '#7460E3FF'}}
                        buttonStyle={{borderColor: '#7367E3', backgroundColor: '#7367E3'}}
                        titleStyle={{color: 'white'}}
                    />
                    :
                    <elements.Button
                        type='outline'
                        title={locale?._('next')}
                        onPress={onSend}
                        // loading={sending}
                        // disabled={sending}
                        loadingProps={{color: '#7460E3FF'}}
                        buttonStyle={{borderColor: '#C6C7CB', backgroundColor: '#C6C7CB'}}
                        titleStyle={{color: 'white'}}
                    />
                }
            </View>
            {/* 交易详情 */}
            <BottomSheet
                isVisible={showDetailPage}
                containerStyle={{ backgroundColor: 'rgba(0.5, 0.25, 0, 0.2)' }}
            >
                <View style={{backgroundColor:"#fff",flexDirection:"column",alignItems:"center"}}>
                    <TouchableOpacity style={{flexDirection:"row",alignItems:"center",backgroundColor:"rgb(246, 246, 246)"}}  onPress={()=>{
                        setShowDetailPage(false);
                    }} activeOpacity={1}>
                        <View style={{width:30}}/>
                        <View style={{height:45,backgroundColor:"rgb(246, 246, 246)",
                            flexDirection:"row",justifyContent:"center",
                            alignItems:"center",paddingRight:15,flex:1
                        }}>
                            <Text style={{fontSize:NFTView_TitleSize}}>{locale._("NFT_Transfer_TranDetail")}</Text>
                        </View>
                        <Icon style={{backgroundColor:"rgb(246, 246, 246)"}} type='feather' name="x" color={'grey'} size={NFTView_TitleSize*1.5} onPress={()=>{
                            setShowDetailPage(false);
                        }} />
                        <View style={{width:15,}}/>
                    </TouchableOpacity>
                    <Text style={{fontSize:NFTView_TitleSize*2,lineHeight:NFTView_TitleSize*5,alignSelf:"center"}}>
                        #{NFT_ID} NFT
                    </Text>
                    <View style={{flexDirection:"row",paddingTop:0,width:width-30,paddingBottom:10,borderBottomWidth:1/scale}}>
                        <Text style={{fontSize:NFTView_TitleSize,color:'grey',width:100 }}>{locale._("NFT_Transfer_Sender")}</Text>
                        <Text style={{fontSize:NFTView_TitleSize,letterSpacing:1/scale,color:'black',flex:1}} numberOfLines={2}>{wallet.address}</Text>
                    </View>
                    <View style={{flexDirection:"row",paddingTop:10,width:width-30,paddingBottom:10,borderBottomWidth:1/scale}}>
                        <Text style={{fontSize:NFTView_TitleSize,color:'grey',width:100 }}>{locale._("NFT_Transfer_receiver")}</Text>
                        <Text style={{fontSize:NFTView_TitleSize,letterSpacing:1/scale,color:'black',flex:1}} numberOfLines={2}>{receiver}</Text>
                    </View>
                    <View style={{flexDirection:"row",paddingTop:10,width:width-30,paddingBottom:10,borderBottomWidth:1/scale,marginBottom:0}}>
                        <Text style={{fontSize:NFTView_TitleSize,color:'grey',width:100 }}>{locale._("NFT_Transfer_ContractAddr")}</Text>
                        <Text style={{fontSize:NFTView_TitleSize,letterSpacing:1/scale,color:'black',flex:1}} numberOfLines={2}>{NFT_Contract}</Text>
                    </View>
                    <View style={{padding:15,width:width,alignItems:"center"}}>
                        {/*<Button title={locale._("NFT_Transfer_Confirm")} onPress={() => {*/}
                        {/*    setShowDetailPage(false);*/}
                        {/*    setShowPwdPage(true);*/}
                        {/*}}/>*/}
                        <elements.Button
                            type='outline'
                            title={locale._("NFT_Transfer_Confirm")}
                            onPress={()=>{
                                setShowDetailPage(false);
                                setShowPwdPage(true);
                            }}
                            // loading={sending}
                            // disabled={sending}
                            loadingProps={{color: '#088DE8'}}
                            buttonStyle={{borderColor: '#088DE8', backgroundColor: '#088DE8'}}
                            titleStyle={{color: 'white'}}
                        />
                    </View>
                </View>
            </BottomSheet>
            {/* 输入密码 */}
            <BottomSheet
                isVisible={showPwdPage}
                containerStyle={{ backgroundColor: 'rgba(0.5, 0.25, 0, 0.2)' }}
            >
                <View style={{backgroundColor:"#fff",flexDirection:"column",alignItems:"center"}}>
                    <TouchableOpacity style={{flexDirection:"row",alignItems:"center",backgroundColor:"rgb(246, 246, 246)"}}  onPress={()=>{
                        setShowPwdPage(false);
                    }} activeOpacity={1}>
                        <View style={{width:30}}/>
                        <View style={{height:45,backgroundColor:"rgb(246, 246, 246)",
                            flexDirection:"row",justifyContent:"center",
                            alignItems:"center",paddingRight:15,flex:1
                        }}>
                            <Text style={{fontSize:NFTView_TitleSize}}>{locale._("NFT_Transfer_InputPwd")}</Text>
                        </View>
                        <Icon style={{backgroundColor:"rgb(246, 246, 246)"}} type='feather' name="x" color={'grey'} size={NFTView_TitleSize*1.5} onPress={()=>{
                            setShowPwdPage(false);
                        }} />
                        <View style={{width:15,}}/>
                    </TouchableOpacity>
                    <Input
                        style={{fontSize: NFTView_TitleSize,padding:0,margin:0}}
                        // allowFontScaling={true}
                        underlineColorAndroid={'transparent'}
                        containerStyle={{padding:0,paddingLeft:15,paddingRight:15,paddingTop:10,height:NFTView_TitleSize*2.5,width:"100%",marginLeft:-10,marginBottom:15}}
                        inputStyle={{padding:0,fontSize:NFTView_TitleSize,lineHeight:NFTView_TitleSize}}
                        inputContainerStyle={{padding:0,height:NFTView_TitleSize*2.5,margin:0}}
                        errorMessage={pwdError}
                        secureTextEntry={!pwdVisible}
                        onChangeText={(value) => {
                            setPwdError("");
                            setPwd(value.trim());
                        }}
                        rightIcon={<Icon
                            name={pwdVisible ? 'eye' : 'eye-off'}
                            type='feather'
                            onPress={() => setPwdVisible(!pwdVisible)}
                        />}
                    />
                    <View style={{padding:15,width:"100%",alignItems:"center"}}>
                        {/*<Button disabled={transfering} title={locale._("NFT_Transfer_Confirm")} onPress={() => {*/}
                        {/*    SendNFT()*/}
                        {/*}}/>*/}
                        <elements.Button
                            type='outline'
                            disabled={transfering}
                            title={locale._("NFT_Transfer_Confirm")}
                            onPress={SendNFT}
                            // loading={sending}
                            // disabled={sending}
                            loadingProps={{color: '#088DE8'}}
                            buttonStyle={{borderColor: '#088DE8', backgroundColor: '#088DE8'}}
                            titleStyle={{color: 'white'}}
                        />
                    </View>
                </View>
            </BottomSheet>
            {/* 发送中 */}
            {/*<Overlay isVisible={waiting}>*/}
            {/*    <View style={{flexDirection:"row",alignItems:"center"}}>*/}
            {/*        <ActivityIndicator animating={true} color={'#0155bc'} size={NFTView_TitleSize*2} style={{marginRight:10}}/>*/}
            {/*        <Text style={{fontSize:NFTView_TitleSize*1.2}}>{locale._("NFT_Transfer_Sending")}</Text>*/}
            {/*    </View>*/}
            {/*</Overlay>*/}
            <WaitingModal show={waiting} prompt={""}/>
            {/* 发送过交易的好友 */}
            <BottomSheet isVisible={recentVisible} modalProps={{
                statusBarTranslucent: true,
                // visible: recentVisible
            }}>
                <View style={{
                    backgroundColor: 'white',
                    borderTopLeftRadius: 5,
                    borderTopRightRadius: 5,
                    minHeight: height / 2,
                    maxHeight: height / 1.5,
                }}>
                    <View style={{
                        flexDirection: 'row',
                        paddingVertical: 20,
                    }}>
                        <Text style={{
                            fontSize: 18,
                            fontWeight: 'bold',
                            textAlign: 'center',
                            flex: 1
                        }}>{locale?._('Assets.send.recent')}</Text>
                        <TouchableOpacity
                            style={{position: 'absolute', padding: 20}}
                            onPress={() => setRecentVisible(false)}
                        >
                            <Icon type='font-awesome' name='close' color='#333333FF' size={24}/>
                        </TouchableOpacity>
                    </View>
                    <ScrollView>
                        {
                            JSON.stringify(recentTxs) !== "[]" && recentTxs != null
                                ?
                                recentTxs.map((tx: any, index: any) => (
                                    <ListItem bottomDivider onPress={() => {
                                        console.log("???")
                                        setRecentVisible(false);
                                        setReceiver(tx.address);
                                        setReceiverError('');
                                    }} key={index}>
                                        <ImageBackground source={logo} style={{width: 38, height: 38}}/>
                                        <ListItem.Content>
                                            <ListItem.Title>{tx.address}</ListItem.Title>
                                            <ListItem.Subtitle>{timeFormat(tx.timestamp)}</ListItem.Subtitle>
                                        </ListItem.Content>
                                    </ListItem>
                                ))
                                :
                                <View style={{flex: 1, justifyContent: 'center'}}>
                                    <Text style={{
                                        // marginTop: 160,
                                        fontSize: 20,
                                        textAlign: 'center',
                                        color: 'grey'
                                    }}>{locale._('noContent')}</Text>
                                </View>
                        }</ScrollView>
                </View>
            </BottomSheet>
        </View>
    )
}

export default NFTSend;


